<template>
  <view class="dialogDetails">
    <view ref="dialogDetails_nav" class="dialogDetails_nav">
      <u-navbar
        bgColor="#ea64a2"
        placeholder
        leftIconColor="#FFFFFF"
        :title="title"
        autoBack
      />
    </view>
    <scroll-view
      scroll-y
      :upper-threshold="15"
      show-scrollbar
      :scroll-top="height.contentHeight"
      :style="{
        height: `${height.window - (height.header + height.footer)}px`,
      }"
      class="dialogDetails_scroll"
      @scrolltoupper="dialogScrolltoupper"
    >
      <u-loadmore
        :status="listQuery.indexStatus"
        loadmoreText="上拉加载更多"
        loadingText="努力加载中"
        nomoreText="实在没有了"
      />
      <view ref="dialogDetails_content" class="dialogDetails_content">
        <view
          v-for="(item, index) in tableData"
          :key="index"
          :class="[
            item.userType === 'user'
              ? 'dialogDetails_content_userItem'
              : 'dialogDetails_content_adminItem',
            'mb20',
          ]"
        >
          <u--image
            :showLoading="true"
            :src="item[item.userType].avatar"
            width="80rpx"
            height="80rpx"
            radius="10rpx"
          />
          <view
            :class="[
              item.userType === 'user'
                ? 'dialogDetails_content_userItem_chat'
                : 'dialogDetails_content_adminItem_chat',
              item.userType === 'user' ? 'mr15' : 'ml15',
            ]"
            >{{ item.content }}</view
          >
        </view>
      </view>
    </scroll-view>
    <view ref="dialogDetails_footer" class="dialogDetails_footer">
      <view class="flex">
        <u--input
          v-model="send.content"
          border="none"
          autoBlur
          focus
          @confirm="sendMessage"
        >
          <text
            v-if="platform === 'h5'"
            slot="suffix"
            class="mr10"
            @click="sendMessage"
            >发送</text
          >
        </u--input>
        <view class="ml15">
          <u-icon size="50rpx" name="/static/dialog/goods.png" />
        </view>
        <view class="ml15" @click="openOrderPopup">
          <u-icon size="50rpx" name="/static/dialog/order.png" />
        </view>
      </view>
      <u-safe-bottom />
    </view>
    <u-popup
      :show="orderPopup.visible"
      closeOnClickOverlay
      round="10"
      @close="closeOrderPopup"
    >
      <scroll-view
        class="dialogDetails_orderPopup"
        style="height: 400px"
        scroll-y
        @scrolltolower="orderPopupScrolltolower"
      >
        <view
          v-for="item in orderPopup.tableData"
          :key="item.id"
          class="dialogDetails_orderPopup_item mb20"
        >
          <view class="dialogDetails_orderPopup_item-header flex">
            <u--image
              :showLoading="true"
              :src="item.admin.avatar[0].url"
              width="50rpx"
              height="50rpx"
              radius="7rpx"
            />
            <view class="flex fs14 ml5" style="color: #606266">
              <text>{{ item.admin.userName || "未命名店铺" }}</text>
              <u-icon name="arrow-right" color="#606266" />
            </view>
          </view>
          <u-line />
          <view
            class="dialogDetails_orderPopup_item-content"
            style="color: #606266"
          >
            <u--image
              :showLoading="true"
              :src="item.goods.iconId[0].url"
              width="200rpx"
              height="200rpx"
              radius="10rpx"
            />
            <view class="dialogDetails_orderPopup_item-content-right ml10">
              <text class="u-line-1 fs14">{{
                item.goods.name || "未命名商品"
              }}</text>
              <view class="flexCol mt10 mb10" style="color: #909399">
                <view
                  v-for="value in item.sku_list"
                  :key="value.id"
                  class="dialogDetails_orderPopup_item-content-right-sku u-line-1 fs13 mb10"
                >
                  <text>{{ value.sku_name_arr.toString() }}</text>
                  <text class="ml5">x{{ value.cart_num }}</text>
                </view>
              </view>
              <view style="color: #ff4b02">
                <text class="fs12">￥</text>
                <text class="fs18">{{ item.sku_list | skuListPrice }}</text>
              </view>
            </view>
          </view>
          <view class="dialogDetails_orderPopup_item-footer fs12">
            <text style="color: #909399">订单备注: </text>
            <text class="ml5" style="color: #606266">{{
              item.descText || "该订单未填写备注"
            }}</text>
          </view>
          <u-line />
          <view class="dialogDetails_orderPopup_item-menu flex">
            <view>
              <u-button
                type="error"
                :plain="true"
                :hairline="true"
                text="发送订单"
                @click="sendOrder(item.id)"
              />
            </view>
          </view>
        </view>
        <u-loadmore
          :status="orderPopup.indexStatus"
          loadmoreText="下拉加载更多"
          loadingText="努力加载中"
          nomoreText="实在没有了"
        />
      </scroll-view>
    </u-popup>
  </view>
</template>

<script>
import { chatRecord } from "@/config/wsRequest.js";
import setSkuData from "@/utils/set_Sku_data.js";
import { mapGetters } from 'vuex'
export default {
  name: "dialogDetails", // 对话详情
  mixins: [setSkuData],
  options: { styleIsolation: "shared" }, // 父组件设置 options.styleIsolation 可穿透子组件，以及页面
  filters: {
    // 计算单个商品里所有sku规格名称
    skuListPrice(sku_list) {
      const prices = sku_list.map((item) => item.price * item.cart_num);
      return prices.length > 0 ? prices.reduce((n, m) => n + m).toFixed(2) : 0;
    },
    setOrderStatusText(type) {
      switch (type) {
        case "YQX":
          return "订单已取消";
        case "DFK":
          return "等待买家付款";
        case "DFH":
          return "等待卖家发货";
        case "DSH":
          return "卖家已发货";
        case "DPJ":
          return "交易成功，待评价";
        case "YWC":
          return "交易成功";
        default:
          return "交易成功，待评价";
      }
    },
  },
  data() {
    return {
      platform: uni.$u.platform, // 当前运行的平台名称（uview封装api方法）
      title: "", // 页面标题
      height: {
        window: 0, // 屏幕高度
        header: 0, // 头部标题高度
        footer: 0, // 底部输入框高度
        contentHeight: 0, // 聊天内容高度
      },
      listQuery: {
        page: 1, // 页码
        size: 20, // 当前页数
        total: 0, // 总数
        pageNum: 0, // 总页数
        groupId: "", // 聊天组id
        indexStatus: "loadmore", // 上拉加载组件状态
      },
      send: {
        content: "", // 发送内容
      },
      tableData: [], // 主数据
      orderPopup: {
        // 订单弹出层
        visible: false,
        indexStatus: "loadmore", // 上拉加载组件状态
        tableData: [], // 订单数据
        page: 1, // 页码
        size: 5, // 页数
        total: 0, // 总数
        pageNum: 0, // 总页数
      },
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  onShow() {
    const routes = getCurrentPages();
    this.listQuery.groupId = routes[routes.length - 1]?.options?.groupId;
    this.title = routes[routes.length - 1]?.options?.title;
    this.listQuery.groupId && this.getList(); // 有聊天组id才获取
    this.getHeight(); // 获取相关高度
    this.getDialogContent(); // 刷新内容高度
    console.log(this.platform, "uni.$u.platform");
  },
  methods: {
    // 聊天内容 scroll-view滚动组件 滚动到顶部/左边，会触发 scrolltoupper 事件
    dialogScrolltoupper() {
      if (this.listQuery.page === this.listQuery.pageNum) {
        // 已到最后一页
        this.listQuery.indexStatus = "nomore";
        return;
      }
      this.listQuery.indexStatus = "loading "; // 开始加载
      this.listQuery.page = this.listQuery.page + 1;
      this.getList();
    },
    // 发送订单
    sendOrder(orderId) {
      this.tableData.push({
        userType: "user",
        messageType: "order",
        user: {
          avatar: "http://files.jiangtao.ltd/10000.jpg",
          userName: "有人@你",
        },
        content: orderId,
      });
      this.closeOrderPopup();
      // 更新高度
      this.$nextTick(() => {
        this.getDialogContent();
      });
    },
    // 订单列表 scroll-view滚动组件 滚动到底部/右边，会触发 scrolltolower 事件
    orderPopupScrolltolower() {
      if (this.orderPopup.page === this.orderPopup.pageNum) {
        // 已到最后一页
        this.orderPopup.indexStatus = "nomore";
        return;
      }
      this.orderPopup.indexStatus = "loading "; // 开始加载
      this.orderPopup.page = this.orderPopup.page + 1;
      this.openOrderPopup();
    },
    // 打开订单弹窗 （获取订单信息）
    async openOrderPopup() {
      const { code, data } = await this.$order.orderGetStatusList(
        this.orderPopup
      );
      if (code === 0) {
        this.orderPopup.tableData.push(...this.setSku(data.list)); // 转化sku格式
        this.orderPopup.total = data.total;
        this.orderPopup.pageNum = data.pageNum;
        this.orderPopup.visible = true;
        if (this.orderPopup.page < this.orderPopup.pageNum) {
          // 未到最后一页，修改为加载更多状态
          this.orderPopup.indexStatus = "loadmore";
        }
      }
    },
    // 关闭订单弹框
    closeOrderPopup() {
      this.orderPopup = {
        // 订单弹出层
        visible: false,
      };
    },
    // 发送消息
    sendMessage() {
      if (!this.send.content) {
        uni.hideKeyboard(); // 收起键盘方法(点击确认没有值时收起键盘)
        return;
      }
      uni.sendSocketMessage({
        data: JSON.stringify({ id: this.userInfo.userId, userType: 'admin', messageType: 'text', content: this.send.content }),
        success: () => {
          this.getList()
          // 清空数据
          this.send = {
            content: "", // 发送内容
          };
        }
      })
    },
    // 获取屏幕相关高度
    async getHeight() {
      const { height: headerHeight } = await this.$cGetRect(
        "dialogDetails_nav",
        this
      ); // 头部高度
      const { height: footerHeight } = await this.$cGetRect(
        "dialogDetails_footer",
        this
      ); // 底部菜单高度
      this.height.window = uni.getSystemInfoSync().screenHeight; // 屏幕高度
      this.height.header = headerHeight;
      this.height.footer = footerHeight;
      console.log("相关高度", this.height);
    },
    // 更新聊天内容高度
    async getDialogContent() {
      const { height: contentHeight } = await this.$cGetRect(
        "dialogDetails_content",
        this
      ); // 聊天具体内容高度
      this.height.contentHeight = contentHeight;
    },
    // 初始化获取数据
    async getList() {
      const { code, data } = await chatRecord(this.listQuery);
      if (code === 0) {
        this.tableData.unshift(...data.list.reverse());
        this.listQuery.total = data.total;
        this.listQuery.pageNum = data.pageNum;
        if (this.listQuery.page < this.listQuery.pageNum) {
          // 未到最后一页，修改为加载更多状态
          this.listQuery.indexStatus = "loadmore";
        }
        if (this.listQuery.page === 1) {
          this.$nextTick(() => {
            this.getDialogContent();
          });
        }
      }
    },
    // 转化sku格式
    setSku(data) {
      data.forEach((item) => {
        if (item.none_sku) {
          item.goods["cart_num"] = item.list[0].cart_num; // 替换成已选择的组合列表（无规格只有一个组合列表数据）
          // 无规格商品
          item["sku_list"] = this.setSku_list(item.goods, "none");
          item["spec_list"] = this.setSpec_list(item.goods.skuList, "none");
        } else {
          item.goods["list"] = item.list; // 替换成已选择的组合列表
          // 多规格商品
          item["sku_list"] = this.setSku_list(item.goods);
          item["spec_list"] = this.setSpec_list(item.goods.skuList);
        }
      });
      return data;
    },
  },
};
</script>

<style lang="scss" scoped>
.dialogDetails {
  &_nav {
    /deep/ .u-navbar__content__title {
      color: #ffffff;
    }
  }
  &_content {
    padding: 10rpx 20rpx;
    &_userItem {
      display: flex;
      flex-direction: row-reverse;
      &_chat {
        background-color: rgba($color: $uni-color-primary, $alpha: 0.3);
        padding: 15rpx 20rpx;
        border-radius: 10rpx;
        max-width: 70%;
        color: #303133;
      }
    }
    &_adminItem {
      display: flex;
      &_chat {
        background-color: #ffffff;
        padding: 15rpx 20rpx;
        border-radius: 10rpx;
        max-width: 70%;
        color: #303133;
      }
    }
  }
  &_footer {
    background-color: #ffffff;
    // position: fixed;
    // bottom: 0;
    // left: 0;
    // width: 100%;
    padding: 15rpx 30rpx;
    /deep/ .u-input {
      background-color: #ebebeb;
      height: 35px;
    }
  }
  &_orderPopup {
    padding: 30rpx 20rpx 20rpx 20rpx;
    background-color: #ebebeb;
    &_item {
      background-color: #fff;
      border-radius: 5rpx;
      padding: 5rpx 10rpx;
      &-content {
        padding: 10rpx 0;
        display: flex;
        &-right {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          &-sku {
            background-color: rgba(0, 0, 0, 0.15);
            width: fit-content;
            padding: 4rpx 10rpx;
          }
        }
      }
      &-footer {
        padding: 5rpx 10rpx;
      }
      &-menu {
        justify-content: right;
        padding: 5rpx 0;
        /deep/ .u-button {
          width: fit-content;
          height: initial !important;
          padding: 6rpx 16rpx !important;
        }
      }
    }
  }
}
</style>
